<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class Users extends Authenticatable
{
    use Notifiable;

    const COLUMN_0 = 0;
    const COLUMN_1 = 1;
    const COLUMN_2 = 2;
    const COLUMN_TEXT = [
        self::COLUMN_1 => '<span class="el-tag el-tag--danger">待审核</span>',
        self::COLUMN_2 => '<span class="el-tag">已审核</span>',
    ];

    const POSITION_1 = 1;
    const POSITION_2 = 2;
    const POSITION_TEXT = [
        self::POSITION_1 => '<span class="el-tag">正常</span>',
        self::POSITION_2 => '<span class="el-tag el-tag--danger">推荐</span>',
    ];

    protected $fillable = [
        'name', 'email', 'password','username','login_at','login_ip','register_ip','integral','created_at','updated_at','avatar',
        'truename','card','company','introduce','column','material','mobile','position','qq_id','weibo_id'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $dates = ['login_at','apply_at'];

    public function article(){
        return $this->hasMany('App\Models\News', 'author_id', 'id');
    }

    /**
     * 列表
     * @param $fields 查询的字段
     * @param $params 条件参数
     * @param int $limit 限制条数
     * @return mixed
     */
    protected function list($fields = ['*'], $params = [], $limit = 10){
        $data = $this->select($fields)
            ->where('id','>',1)
            ->where(function ($query) use ($params) {
                if($params['title']) $query ->where('truename', 'like', '%'.$params['title'].'%')->orWhere('introduce', 'like', '%'.$params['title'].'%');
            })
            ->where('column',self::COLUMN_2)
            ->paginate($limit)
            ->toArray();
        foreach($data['data'] as &$item){
            //统计文章数
            $total_news = News::countNews($item['id']);
            //统计浏览量
            $total_views = News::countViews($item['id']);
            $item['total_news']  = $total_news;
            $item['total_views'] = $total_views;
        }
        return $data;
    }

    /**
     * 专栏作者
     * @return mixed
     */
    protected function authors(){
        $data = $this->select('id','truename','avatar','created_at')
            ->where('position',self::POSITION_2)
            ->where('column',self::COLUMN_2)
            ->inRandomOrder()
            ->take(3)
            ->get()
            ->toArray();
        foreach($data as &$item){
            //统计文章数
            $total_news = News::countNews($item['id']);
            $list = News::where('status',News::STATUS_1)->where('author_id',$item['id'])->select(['id','title'])->take(3)->get()->toArray();
            $item['article']  = $list;
                //统计浏览量
            $total_views = News::countViews($item['id']);
            $item['total_news']  = $total_news;
            $item['total_views'] = $total_views;
        }
        return $data;
    }

}
